/**
 * 
 */
package org.swing.utility.jai.util;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import javax.media.jai.PlanarImage;
import javax.swing.JScrollPane;
import javax.swing.JViewport;

import com.sun.media.jai.widget.DisplayJAI;

/**
 * @author  Le Quynh Nhu
 *
 */
public class jaiGUI extends javax.swing.JFrame {

	public jaiGUI() {
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	private static final long serialVersionUID = -7704521243122639729L;
	private static long nextDisplayTime = System.currentTimeMillis();
	private static long displayIntervalInMilis = 300;

	PlanarImage displayedImage = null;

	public void display(PlanarImage imageToDisplay) {
		displayedImage = imageToDisplay;
		if (imageToDisplay == null) {
			this.setVisible(false);
			try {
				//SwingUtilities.updateComponentTreeUI(this);
			} catch (Exception e) {
			}
			return;
		}
		if (System.currentTimeMillis() < nextDisplayTime) {
			return;
		}
		nextDisplayTime = System.currentTimeMillis() + displayIntervalInMilis;

		this.getContentPane().removeAll();

		
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent event) {
				System.exit(0);
			}
		});

		JScrollPane jImagePanel = new JScrollPane(null);

		BufferedImage resultImage = displayedImage.getAsBufferedImage();
		int corr_r = 30 + 1;
		int corr_h = 19;

		Dimension frameDim = new Dimension(resultImage.getWidth() + corr_r
				- corr_h, resultImage.getHeight() + corr_r);

		this.setSize((int) frameDim.getWidth(), (int) frameDim.getHeight());
		this.setPreferredSize(frameDim);

		DisplayJAI jaiDisplay = new DisplayJAI(resultImage);

		jImagePanel.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
		jImagePanel.getViewport().setView(jaiDisplay);
		this.setLocation((int) Toolkit.getDefaultToolkit().getScreenSize()
				.getWidth()
				/ 2 - resultImage.getWidth() / 2, (int) Toolkit
				.getDefaultToolkit().getScreenSize().getHeight()
				/ 2 - resultImage.getHeight() / 2);

		jImagePanel.repaint();
		jImagePanel.revalidate();

		this.getContentPane().add(jImagePanel, BorderLayout.CENTER);
		this.setVisible(true);
	}
}
